package v1

import (
	"go_api/pkg/app"
	"go_api/pkg/e"
	"go_api/pkg/setting"
	"go_api/pkg/util"
	"go_api/service/assignment_service"
	"go_api/service/user_service"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetAssignments(c *gin.Context) {
	appG := app.Gin{C: c}
	claims := c.MustGet("claims").(*util.Claims)
	status := c.DefaultQuery("status", "unstart")
	assignment := assignment_service.Assignment{
		Status:      status,
		StudentId:   claims.ID,
		PageNum:     util.GetPage(c),
		PageSize:    setting.AppSetting.PageSize,
	}
	assignments, err := assignment.GetAll()
	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
	}

	total, _ := assignment.Count()
	ids := []int{}
	for _, assignment := range assignments {
		ids = append(ids, assignment.StudentId, assignment.CreatedBy)
	}
	ids = util.RemoveRepeatedElement(ids)
	users, err := user_service.GetIdsUsers(ids)

	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
	}
	for _, assignment := range assignments{
		for _, user := range users{
			if user.ID == assignment.StudentId {
				assignment.Student.Username = user.Username
				assignment.Student.ID       = user.ID
			}
			if user.ID == assignment.CreatedBy {
				assignment.Teacher.ID = user.ID
				assignment.Teacher.Username = user.Username
			}
		}
	}

	data := make(map[string]interface{})
	data["lists"] = assignments
	data["total"] = total
	appG.Response(http.StatusOK, data)
}
